package com.satan.vote.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.satan.vote.dto.VoteDTO;
import com.satan.vote.entity.Vote;
import com.satan.vote.entity.VoteDetail;
import com.satan.vote.entity.VoteItem;
import com.satan.vote.entity.WxUserInfo;
import com.satan.vote.mapper.VoteMapper;
import com.satan.vote.service.VoteDetailService;
import com.satan.vote.service.VoteItemService;
import com.satan.vote.service.VoteService;
import com.satan.vote.service.WxUserInfoService;
import com.satan.vote.util.DateUtil;
import com.satan.vote.util.JwtUtils;
import com.satan.vote.vo.ResultVO;
import com.satan.vote.vo.VoteVO;
import io.jsonwebtoken.Claims;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.mybatisflex.core.query.QueryMethods.select;

/**
 * @ClassName VoteServiceImpl
 * @Description TODO
 * @date 2023/8/13 14:27
 * @Version 1.0
 */
@Service
public class VoteServiceImpl extends ServiceImpl<VoteMapper, Vote> implements VoteService {
    @Value("${coverImagesFilePath}")
    private String coverImagesFilePath;
    @Autowired
    private ResourceLoader resourceLoader;
    @Autowired
    private VoteItemService voteItemService;
    @Autowired
    private WxUserInfoService wxUserInfoService;
    @Autowired
    private VoteDetailService voteDetailService;
    @Override
    public ResultVO uploadCoverImage(MultipartFile coverImage) {
        System.out.println("filename:"+coverImage.getName());
        Map<String,Object> resultMap=new HashMap<>();
        if(!coverImage.isEmpty()){
// 获取文件名
            String originalFilename = coverImage.getOriginalFilename();
            String suffixName=originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFileName= DateUtil.getCurrentDateStr()+suffixName;
            String uniappFolderPath = null;
            try {
                // 获取 resources 目录的路径
                String resourcesPath = resourceLoader.getResource("classpath:").getFile().getAbsolutePath();

                // 拼接 uniapp 文件夹的路径
                uniappFolderPath = resourcesPath + File.separator + coverImagesFilePath;

                // 创建 Path 对象
                Path uniappFolder = Paths.get(uniappFolderPath);

                // 判断 uniapp 文件夹是否存在
                if (Files.exists(uniappFolder) && Files.isDirectory(uniappFolder)) {
                    System.out.println("uniapp 文件夹已存在");
                } else {
                    // 创建 uniapp 文件夹
                    Files.createDirectory(uniappFolder);
                    System.out.println("uniapp 文件夹创建成功");
                }
            } catch (Exception e) {
                System.out.println("发生异常：" + e.getMessage());
            }
            try {
                FileUtils.copyInputStreamToFile(coverImage.getInputStream(), new File(uniappFolderPath, newFileName));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            resultMap.put("coverImageFileName",newFileName);
            return ResultVO.success(resultMap);
        }
        return ResultVO.fail(500,"上传失败");
    }

    @Override
    @Transactional
    public ResultVO add(VoteDTO voteDTO, String token) {
        System.out.println("token="+token);
        Claims claims = JwtUtils.validateJWT(token).getClaims();
        System.out.println("openid="+claims.getId());
        voteDTO.setOpenid(claims.getId());
        Vote vote = new Vote();
        BeanUtil.copyProperties(voteDTO, vote,false);
        save(vote);
// 存投票选项
        List<VoteItem> voteItemList=voteDTO.getVoteItemList();
        for(VoteItem voteItem:voteItemList){
            voteItem.setVoteId(vote.getId());
            voteItem.setNumber(0);
            voteItemService.add(voteItem);
        }
        return ResultVO.success(null);
    }

    @Override
    public ResultVO listOfUser(String token) {
        Claims claims = JwtUtils.validateJWT(token).getClaims();
        QueryWrapper queryWrapper = QueryWrapper.create().where(Vote::getOpenid).eq(claims.getId()).orderBy(Vote::getVoteEndTime).desc();
        List<Vote> voteList = list(queryWrapper);
        return ResultVO.success(voteList);
    }

    @Override
    public ResultVO findById(Integer id) {
        Vote vote = getById(id);
        QueryWrapper queryWrapper = QueryWrapper.create().where(WxUserInfo::getOpenid).eq(vote.getOpenid());
        WxUserInfo wxUserInfo = wxUserInfoService.getOne(queryWrapper);
        VoteVO voteVO = new VoteVO();
        BeanUtil.copyProperties(vote,voteVO , true);
        voteVO.setWxUserInfo(wxUserInfo);
        queryWrapper=QueryWrapper.create().where(VoteItem::getVoteId).eq(id);
        List<VoteItem> voteItemList = voteItemService.list(queryWrapper);
        voteVO.setVoteItemList(voteItemList);
        return ResultVO.success(voteVO);
    }

    @Override
    public ResultVO listOfJoinUser(String token) {
        Claims claims = JwtUtils.validateJWT(token).getClaims();
//        List<Vote> voteList = list(new QueryWrapper<Vote>().inSql("id", "SELECT vote_id FROM t_vote_detail WHERE openid='" + claims.getId() + "'").orderByDesc("vote_end_time"));
//        SELECT * FROM t_vote WHERE id IN (SELECT vote_id FROM t_vote_detail WHERE
//        openid='o30ur5JpAsAUyGBkR0uW4IxvahR8')
        QueryWrapper queryWrapper = QueryWrapper.create().where(Vote::getId).in(select().from("tb_vote_detail").select("id").where(VoteDetail::getOpenid).eq(claims.getId()));
        List<Vote> voteList = list(queryWrapper);
        return ResultVO.success(voteList);
    }

    @Override
    @Transactional
    public ResultVO delete(Integer id) {
        //删除用户投票详情
        QueryWrapper queryWrapper = QueryWrapper.create().where(VoteDetail::getVoteId).eq(id);
        boolean remove1 = voteDetailService.remove(queryWrapper);
        //删除投票选项
        queryWrapper = QueryWrapper.create().where(VoteItem::getVoteId).eq(id);
        boolean remove2 = voteItemService.remove(queryWrapper);
        //删除投票
        boolean remove3 = removeById(id);
       if (remove1 && remove2 && remove3){
           return ResultVO.success(null);
       }else {
           return ResultVO.fail(500,"删除失败");
       }

    }


}
